package com.lanyuan.util;

import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.reflect.FieldUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;

public class Kit {
	public static final String yyyy_MM_dd = "yyyy-MM-dd";
	public static final String yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";
	public static final String yyyy_MM_dd_HH_mm_ss_SSS = "yyyyMMddHHmmssSSS";

	private static final SimpleDateFormat SDF = new SimpleDateFormat();

	private static final Logger log = Logger.getLogger(Kit.class);

	/**
	 * 将毫秒转为制定yyyy-MM-dd格式的时间字符串
	 * 
	 * @param value
	 *            毫秒
	 * @return
	 */
	public static String formatToyyyy_MM_dd(long value) {
		return DateFormatUtils.format(value, yyyy_MM_dd);
	}

	/**
	 * 将date转为制定yyyy-MM-dd格式的时间字符串
	 * 
	 * @param value
	 *            java Date
	 * @return
	 */
	public static String formatToyyyy_MM_dd(Date value) {
		return DateFormatUtils.format(value, yyyy_MM_dd);
	}

	public static String formatToyyyy_MM_dd_HH_mm_ss(long value) {
		return DateFormatUtils.format(value, yyyy_MM_dd_HH_mm_ss);
	}

	public static String formatToyyyy_MM_dd_HH_mm_ss(Date value) {
		return DateFormatUtils.format(value, yyyy_MM_dd_HH_mm_ss);
	}

	public static String formatToyyyy_MM_dd_HH_mm_ss_SSS(long value) {
		return DateFormatUtils.format(value, yyyy_MM_dd_HH_mm_ss_SSS);
	}

	public static String formatToyyyy_MM_dd_HH_mm_ss_SSS(Date value) {
		return DateFormatUtils.format(value, yyyy_MM_dd_HH_mm_ss_SSS);
	}

	public static String format(Date value, String format) {
		return DateFormatUtils.format(value, format);
	}

	/**
	 * 将yyyy-MM-dd格式字符串转为date
	 * 
	 * @param value
	 * @return
	 */
	public static Date parseToDate(String value, String format) {
		try {
			SDF.applyPattern(format);
			return SDF.parse(value);
		} catch (Exception e) {
			log.warn("parseToyyyy_MM_dd fail ");
			return null;
		}
	}

	/**
	 * 获得前一天的时间间隔
	 * 
	 * @return
	 */
	public static Date[] getDayBeforeTimeInterval() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_YEAR, -1);

		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		Date startTime = cal.getTime();

		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		cal.set(Calendar.MILLISECOND, 999);
		Date endTime = cal.getTime();

		return new Date[] { startTime, endTime };

	}

	/**
	 * 获得当前天的前一天的时间间隔
	 * 
	 * @return
	 */
	public static Date[] getDayBeforeTimeInterval(Date currentDate) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(currentDate);
		cal.add(Calendar.DAY_OF_YEAR, -1);

		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		Date startTime = cal.getTime();

		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		cal.set(Calendar.MILLISECOND, 999);
		Date endTime = cal.getTime();

		return new Date[] { startTime, endTime };

	}

	/**
	 * 获得一个月的间隔时间
	 * 
	 * @return
	 */
	public static Date[] getMonthInterval(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.clear();
		cal.setTime(date);

		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		Date startTime = cal.getTime();

		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		cal.set(Calendar.MILLISECOND, 999);
		cal.set(Calendar.DAY_OF_MONTH, getMonthMaxDay(date));
		Date endTime = cal.getTime();

		return new Date[] { startTime, endTime };

	}

	/**
	 * 获得一个年的间隔时间
	 * 
	 * @return
	 */
	public static Date[] getYearInterval(Integer year) {
		Calendar cal = Calendar.getInstance();
		cal.clear();

		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		cal.set(Calendar.MONTH, 0);
		cal.set(Calendar.YEAR, year);

		Date startTime = cal.getTime();

		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		cal.set(Calendar.MILLISECOND, 999);
		cal.set(Calendar.DAY_OF_MONTH, 31);
		cal.set(Calendar.MONTH, 11);
		cal.set(Calendar.YEAR, year);
		Date endTime = cal.getTime();

		return new Date[] { startTime, endTime };

	}

	/**
	 * 将类的静态变量封装成map 返回
	 * 
	 * @param classzz
	 * @return
	 */
	public static <T> Map<String, Object> classStaticFiled2Map(Class<T> classzz) {
		Map<String, Object> map = new HashMap<String, Object>();
		Field[] fields = classzz.getFields();

		for (Field field : fields) {
			try {
				map.put(field.getName(), FieldUtils.readStaticField(field));

			} catch (IllegalAccessException e) {
				log.warn("classStaticFiled2Map fail ");
			}
		}
		return map;
	}

	/**
	 * 获得request ip
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		try {
			String ip = request.getHeader("x-forwarded-for");
			if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
			}
			if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			}
			if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}

			if ("0:0:0:0:0:0:0:1".equals(ip)) {
				ip = "127.0.0.1";
			}

			return ip;
		} catch (Exception e) {

		}

		return "";
	}

	/**
	 * 通过IP地址获取MAC地址
	 * 
	 * @param ip
	 *            String,127.0.0.1格式
	 * @return mac String
	 * 
	 */
	public static String getMACAddress(String ip) {
		try {
			String line = "";
			String macAddress = "";
			final String MAC_ADDRESS_PREFIX = "MAC Address = ";
			final String LOOPBACK_ADDRESS = "127.0.0.1";
			// 如果为127.0.0.1,则获取本地MAC地址。
			if (LOOPBACK_ADDRESS.equals(ip)) {
				InetAddress inetAddress = InetAddress.getLocalHost();

				byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
				// 下面代码是把mac地址拼装成String
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < mac.length; i++) {
					if (i != 0) {
						sb.append("-");
					}
					// mac[i] & 0xFF 是为了把byte转化为正整数
					String s = Integer.toHexString(mac[i] & 0xFF);
					sb.append(s.length() == 1 ? 0 + s : s);
				}
				// 把字符串所有小写字母改为大写成为正规的mac地址并返回
				macAddress = sb.toString().trim().toUpperCase();
				return macAddress;
			}
			// 获取非本地IP的MAC地址
			/*
			 * try { Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
			 * InputStreamReader isr = new
			 * InputStreamReader(p.getInputStream()); BufferedReader br = new
			 * BufferedReader(isr); while ((line = br.readLine()) != null) { if
			 * (line != null) { int index = line.indexOf(MAC_ADDRESS_PREFIX); if
			 * (index != -1) { macAddress = line.substring(index +
			 * MAC_ADDRESS_PREFIX.length()).trim().toUpperCase(); } } }
			 * br.close(); } catch (IOException e) { e.printStackTrace(); }
			 */
			return macAddress;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "";

	}

	/**
	 * 获得指定时间处于月的第几天(下标从1开始)
	 * 
	 * @param date
	 * @return
	 */
	public static int getDayMonth(Date date) {
		return (int) DateUtils.getFragmentInDays(date, Calendar.MONTH);
	}

	/**
	 * 获得指定时间的月最大天数(下标从1开始)
	 * 
	 * @param date
	 * @return
	 */
	public static int getMonthMaxDay(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.clear();
		cal.setTime(date);
		return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
	}

}
